package com.djx.comm.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dingjunxiong
 */
public class JsonUtil {

	private static final SerializeConfig config;
	static {
		config = new SerializeConfig();
	}

	private static final SerializerFeature[] features = {
			// 输出空置字段
			SerializerFeature.WriteMapNullValue,
			// list字段如果为null，输出为[]，而不是null
			SerializerFeature.WriteNullListAsEmpty,
			// 数值字段如果为null，输出为0，而不是null
			SerializerFeature.WriteNullNumberAsZero,
			// Boolean字段如果为null，输出为false，而不是null
			SerializerFeature.WriteNullBooleanAsFalse,
			// 字符类型字段如果为null，输出为""，而不是null
			SerializerFeature.WriteNullStringAsEmpty

	};

	public static final Object parse(String jsonStr){
		return JSON.parse(jsonStr);
	}
	
	public static String toJSONString(Object object) {
		return JSON.toJSONString(object, config,features);
	}
	
	public static final String toJSONString(Object object, SerializeFilter filter, SerializerFeature... features) {
		return JSON.toJSONString(object, filter, features);
	}

	public static String toJSONStringWithDateFormat(Object object, String dateFormat) {
		return JSON.toJSONStringWithDateFormat(object, dateFormat, features);
	}

	public static JSONObject parseObject(String jsonStr) {

		return JSON.parseObject(jsonStr);
	}

	public static final <T> T parseObject(String jsonStr, Class<T> clazz, Feature... features) {
		return JSON.parseObject(jsonStr, clazz, features);
	}

	public static final <T> T parseObject(String jsonStr, Type clazz, Feature... features) {
		return (T)JSON.parseObject(jsonStr, clazz, features);
	}

	public static JSONArray parseArray(String jsonStr) {

		return JSON.parseArray(jsonStr);
	}

	public static final <T> List<T> parseArray(String jsonStr, Class<T> clazz) {
		return JSON.parseArray(jsonStr, clazz);
	}

	public static final List<Object> parseArray(String jsonStr, Type[] types) {
		return JSON.parseArray(jsonStr, types);
	}

	public static final <T> T toJavaObject(JSON json, Class<T> clazz) {
		
		return JSON.toJavaObject(json, clazz);
	}
	
	public static void main(String[] args) {
		Map map = new HashMap();
		Double d =null;
		
		map.put("sss", d);
		System.out.println(toJSONString(map));
		System.out.println(toJSONStringWithDateFormat(map, "yyyy-MM-dd"));
		
	}

}
